import axios from 'axios';
import { useRouter } from 'next/router';
import { useEffect, useState } from 'react';
import Seo from '@/core/components/Seo';
import dynamic from 'next/dynamic';
import { get } from 'lodash-contrib';
import { getIdFromSlug, getNameFromSlug } from '@/core/utils/slug';

const BasicLayout = dynamic(() =>
  import('@/core/components/layouts/BasicLayout')
);
const ProductSearch = dynamic(() =>
  import('@/lib/product/components/ProductSearch')
);

const BASE_URL = 'https://indoteknik.com';
export default function FindPage() {
  const route = useRouter();
  const qSlug = route?.query?.slug || null;
  const url = BASE_URL + route.asPath;
  const [result, setResult] = useState(null);
  const [query, setQuery] = useState(null);

  const slug = qSlug ? getNameFromSlug(route?.query?.slug) +' '+ getIdFromSlug(route?.query?.slug) : '';
  const getUrls = async (url) => {
    try {
      let response = await axios(
        `${process.env.NEXT_PUBLIC_SELF_HOST}/api/shop/url-category_brand?url=${url}`
      );
      let result = response?.data?.response?.docs[0] || null;
      setResult(result);
    } catch (error) {
      console.error('Error fetching data:', error);
    }
  };

  useEffect(() => {
    getUrls(url);
  }, []);

  useEffect(() => {
    if (result) {
      let fq = `category_parent_ids:${result.category_id_i} AND manufacture_id_i:${result.brand_id_i}`;
      setQuery({
        fq: fq,
      });
    }
  }, [result]);

  return (
    <BasicLayout>
      <Seo
        title={`Jual ${slug} original - indoteknik.com`}
        description={`Jual ${slug} Kirim Jakarta Surabaya Semarang Makassar Manado Denpasar Balikpapan Medan Palembang Lampung Bali Bandung Makassar Manado.`}
        additionalMetaTags={[
          {
            property: 'keywords',
            content: `Jual ${slug}, harga ${slug}, ${slug} murah, toko ${slug}, ${slug} jakarta, ${slug} surabaya`,

          },
        ]}
      />
      {query && <ProductSearch query={query} prefixUrl={`${route.asPath}`} />}
    </BasicLayout>
  );
}
